var express = require('express');
var router = express.Router();
var logger = require('../libs/log');
var OSHandle = require('../libs/os');
var ipLIB = require('../libs/ipip')();
// var ipLIB = require('../libs/ip');
var then = require('thenjs');
var tools = require('../libs/tools');
var moment = require('moment');
var detector = require('detector');
var baiduSearchLIB = require('../libs/baiduSearch');
var fs = require('fs');
var imgContent =  fs.readFileSync('./public/images/1_1.gif',"binary");
var index = function(req, res, next) {
	var headers = req.headers;
	var ua = headers['user-agent'].toLowerCase();
	var useragentInfo = req.useragent;
	var logData = {
		method: req.method,
		isNew: false,
		originalUrl: req.originalUrl,
	};
	var whitelists = ['cid','sid','referer','eventID','url','color','resolution','flash','java','customize'];
	var query = req.query;
	var NASID = req.cookies['NASID'];
	var session = req.cookies['session'];
	var ip = tools.getClientAddress(req);

    if(!NASID){
    	logData['isNew'] = true;
        var NASID = tools.guid();
        res.cookie('NASID', NASID, { expires: new Date(Date.now() + 1000*60*60*24*30*36)});
    }
    if(!session){
        var session = tools.guid();
        res.cookie('session', session);
    }

	then(function (defer) {
		var ipinfo = ipLIB(ip);
		if(!ipinfo||ipinfo.code == 1){
			ipinfo = {};
		}
		// 添加url query中的数据
		for (var i = 0; i < whitelists.length; i++) {
			var item = whitelists[i];
			if(query[item] !== undefined){
				logData[item] = query[item];
			}
		};
		var engineData = tools.getEngine(query['referer']);
		if(typeof engineData[0] == "undefined")engineData[0] = '';
		if(typeof engineData[1] == "undefined")engineData[1] = '';
		logData['isPay'] = engineData[2];
		var detectorData = detector.parse(ua);
		// 从http header中获取的数据
		logData['NASID'] = NASID;
		logData['session'] = session;
		logData['ep'] = headers['referer'] || ''
		logData['cookie'] = headers['cookie'] || '';
		logData['se'] = engineData[0];
		// 添加站内搜索
		var queryKey = query['queryKey'];
		try{
			if(queryKey){
				logData['sis'] = tools.getQueryString(queryKey,logData['ep']);
				if(query['url']){
					logData['sisURL'] = decodeURIComponent(query['url']);
				}
			}
			logData['query'] = decodeURIComponent(engineData[1]);
		}catch(e){
			console.info("~~~~~~~~query['referer']",query['referer']);
			logData['query'] = '';
		}
		logData['refererType'] = tools.getRefererType(query['referer'],logData['ep'],engineData[0]);
		logData['ip'] = ip;
		logData['lang'] = tools.getLanguage(headers['accept-language']);

		logData['browser'] = detectorData['browser']['name'];
		if(logData['browser'] == 'na'){
			logData['browser']='';
		}else{
			logData['browser'] = tools.getBrowserName(logData['browser']);
		}

		logData['version'] = detectorData['browser']['fullVersion'];
		if(logData['version'] == -1){
			logData['version'] = '';
		}
		logData['os'] = OSHandle['getOS'](detectorData['os']['name'],detectorData['os']['fullVersion'],detectorData['os']['version']);
		logData['device'] = detectorData['device']['name'];
		if(logData['device'] == 'na'){
			logData['device']='';
		}
		if(logData['device']){
			logData['device'] = tools.getDeviceName(logData['device'])
		}
		if(detectorData['device']['fullVersion'] != -1){
			logData['device'] += ' '+detectorData['device']['fullVersion'];
		}
		logData['platform'] = useragentInfo['platform'];
		logData['isMobile'] = useragentInfo['isMobile'];
		logData['isTablet'] = useragentInfo['isTablet'];
		logData['isDesktop'] = useragentInfo['isDesktop'];
		logData['isWindows'] = useragentInfo['isWindows'];
		logData['isMac'] = useragentInfo['isMac'];
		logData['isLinux'] = useragentInfo['isLinux'];
		logData['userAgent'] = useragentInfo['source'];
		if(logData['isMobile']){
			logData['isTablet'] = false;
			logData['isDesktop'] = false;
		}
		if(logData['isTablet']||logData['device']=='iPad'){
			logData['isTablet'] = true;
			logData['isMobile'] = false;
			logData['isDesktop'] = false;
		}
		if(logData['isDesktop']||logData['device']=='桌上电脑'){
			logData['isDesktop'] = true;
			logData['isMobile'] = false;
			logData['isTablet'] = false;
		}
		// 系统自动生成的字段
		var time = moment().valueOf();
		logData['time'] = time;
		logData['timeY'] = moment(time).year();
		logData['timeM'] = moment(time).month()+1;
		logData['timeD'] = moment(time).date();
		logData['timeH'] = moment(time).hour();
		// IP地址解析的字段
		if(ipinfo['country']){
			logData['country'] = ipinfo['country'];
			logData['countryID'] = '';//ipinfo['country_id'];
			logData['area'] = '';//ipinfo['area'];
			logData['areaID'] = '';//ipinfo['area_id'];
			logData['region'] = tools.getProvinceName(ipinfo['province']);//ipinfo['region'];
			logData['regionID'] = '';//ipinfo['region_id'];
			logData['city'] = tools.getCityName(ipinfo['city']);//ipinfo['city'];
			logData['cityID'] = '';//ipinfo['city_id'];
			logData['county'] = '';//ipinfo['county'];
			logData['countyID'] = '';//ipinfo['county_id'];
			logData['isp'] = '';//ipinfo['isp'];
			logData['ispID'] = '';//ipinfo['isp_id'];
		}
		// ipinfo
		if(logData['se'] == 'baidu'){
			baiduSearchLIB.cacheLog(logData);
		}else{
			logger.logger(logData);
		}
	})
	if(query['url']){
		res.redirect(query['url']);
	}else if(res.locals.imageview){
		res.writeHead('200', {'Content-Type': 'image/gif'});
		res.end(imgContent,'binary');
	}else{
		res.writeHead('200', {'Content-Type': 'application/x-javascript'});
		res.end('');
	}
}

var baiduSearch = function(req, res, next) {
	var referer = req.body.url;
	var query = req.body.fromType;
	baiduSearchLIB.getLogData(referer,query);
	res.send('ok');
}
router.get('/', index);
router.get('/imageview', function(req, res, next){
	res.locals.imageview = true;
	index(req, res, next);
});
router.post('/baiduSearch', baiduSearch);

module.exports = router;
